<template>
  <div class="social-callback">
    <div class="callback-container">
      <el-icon class="is-loading"><loading /></el-icon>
      <span>{{ loadingText }}</span>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus';
import { Loading } from '@element-plus/icons-vue';
import { getCurrentInstance, onMounted, ref } from 'vue';

const instance = getCurrentInstance();
const setGlobalState = instance?.appContext.config.globalProperties.$setGlobalState;
const messageService = instance?.appContext.config.globalProperties.$messageService;

const loadingText = ref('正在处理社交登录...');

onMounted(async () => {
  try {
    // 获取 URL 参数
    const urlParams = new URLSearchParams(window.location.search);
    const code = urlParams.get('code');
    const state = urlParams.get('state');

    if (!code) {
      throw new Error('授权码不存在');
    }

    loadingText.value = '正在验证授权信息...';

    // 这里应该调用后端 API 处理社交登录
    // const response = await socialLogin({ code, state });

    // 模拟处理
    await new Promise((resolve) => setTimeout(resolve, 2000));

    const userInfo = {
      username: 'social_user',
      nickname: '社交用户',
      avatar: 'https://avatars.githubusercontent.com/u/1?v=4',
      roles: ['user'],
      permissions: ['system:user:list'],
    };

    const token = `social-token-${Date.now()}`;

    // 通知主应用登录成功
    if (setGlobalState) {
      setGlobalState({
        user: userInfo,
        token,
        isLogin: true,
      });
    }

    if (messageService) {
      messageService.broadcast('user:login', {
        user: userInfo,
        token,
      });
    }

    ElMessage.success('社交登录成功');

    // 跳转到主应用
    setTimeout(() => {
      window.location.href = '/';
    }, 1000);
  } catch (error) {
    console.error('社交登录失败:', error);
    ElMessage.error(`社交登录失败: ${(error as Error).message}`);

    // 跳转回登录页
    setTimeout(() => {
      window.location.href = '/login';
    }, 2000);
  }
});
</script>

<style lang="less" scoped>
.social-callback {
  width: 100%;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

  .callback-container {
    padding: 40px;
    background: var(--el-bg-color);
    border-radius: var(--el-border-radius-base);
    box-shadow: var(--el-box-shadow-light);
  }
}
</style>
